package com.yksj.healthtalk.ui.doctorstation;

import java.util.ArrayList;
import java.util.List;

import org.universalimageloader.core.ImageLoader;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.MainTabUI;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.ServerCenterListActivity;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.buyandsell.BuyAndSellMainActivity;
import com.yksj.healthtalk.ui.doctorstation.active.ActivesListActivity;
import com.yksj.healthtalk.ui.doctorstation.service.DoctorQuerySubscribeServiceActivity;
import com.yksj.healthtalk.ui.messageleave.DoctorMessageBoardDoctor;
import com.yksj.healthtalk.ui.salon.SalonAboutOthersActivity;
import com.yksj.healthtalk.ui.setting.PersonalInformationActivity;
import com.yksj.healthtalk.ui.views.CirclePageIndicator;
import com.yksj.healthtalk.utils.SharePreUtils;
import com.yksj.healthtalk.utils.ViewUtils;
/**
 * 我的诊所
 * @author jack_tang
 *
 */
public class DoctorHomeMainActivity extends BaseFragmentActivity implements OnClickListener {

	private ViewPager mViewPager;
	private CirclePageIndicator mIndicator;
	private ImageLoader imageLoader;
	private TabsPagerAdapter adapter;
	
	final BroadcastReceiver receiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_LEAVE_WORD)) {
//				if(adapter!= null&&adapter.messageNumber!=null){
//					adapter.messageNumber.setText(intent.getStringExtra(MessagePushService.BROAD_KEY));
//					adapter.messageNumber.setVisibility(View.VISIBLE);
//				}
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_home_main_activity_layout);
		HTalkApplication.onHandleCrashedLogin(arg0,this);
		imageLoader = ImageLoader.getInstance();
		HttpRestClient.doHttpEnterhome();
		initUI();
	}

	
	private void initUI() {
		initTitle();
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText("我的诊所");
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setOnClickListener(this);
		
		if(SharePreUtils.fatchLockState()){
			titleRightBtn2.setText("取消设首页");
		}else{
			titleRightBtn2.setText("设首页");
		}
		
		mViewPager = (ViewPager)findViewById(R.id.myviewpager);
		mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
		adapter = new TabsPagerAdapter();
		mViewPager.setAdapter(adapter);
		mIndicator.setViewPager(mViewPager);
		findViewById(R.id.top_line).setVisibility(View.GONE);
		//医生等级
		ImageView doctorLevel= (ImageView) findViewById(R.id.user_level);
		doctorLevel.setImageLevel(SmartFoxClient.getLoginUserInfo().getDoctorLevel());
	}

	@Override
	public void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		filter.addAction(MessagePushService.ACTION_LEAVE_WORD);
		registerReceiver(receiver, filter);
		super.onStart();
		Intent intent =new Intent(this,CoreService.class);
		intent.setAction(CoreService.ACTION_FRAME_VIEW_VISIABLE);
		intent.putExtra("className",this.getClass().getName());
		startService(intent);
	}

	@Override
	public void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		ImageView user_icon= (ImageView) findViewById(R.id.user_icon);
		user_icon.setOnClickListener(this);
		TextView user_id= (TextView) findViewById(R.id.user_id);
		TextView user_name= (TextView) findViewById(R.id.user_name);
		
		CustomerInfoEntity userInfo = SmartControlClient.getControlClient().getInfoEntity();
		
		ImageView user_sex_icon= (ImageView) findViewById(R.id.user_sex_icon);
		user_sex_icon.setImageLevel(Integer.valueOf(userInfo.getSex()));
		
		user_id.setText(userInfo.getUsername());
		user_name.setText(userInfo.getName());
		imageLoader.displayImage(userInfo.getSex(),userInfo.getNormalHeadIcon(), user_icon);
		//未读消息
		queryDataCountoOther();
	}
	
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.title_back:
//			onBackPressed();
			intent=new Intent(this, MainTabUI.class);
			startActivity(intent);
			HttpRestClient.doHttpExithome();
			break;
		case R.id.user_icon://医生资料
			intent = new Intent(this,PersonalInformationActivity.class);
			this.startActivity(intent);
			break;
		case R.id.my_calendar://日历
			intent = new Intent(this,DoctorQuerySubscribeServiceActivity.class);
			startActivity(intent);
			break;
		case R.id.my_huanzhe://患者管理
			intent = new Intent(this,PatientServiceMainFragmentList.class);
			startActivity(intent);
			break;
		case R.id.my_bingan://合作者
//			SingleBtnFragmentDialog.show(getSupportFragmentManager(),"壹健康","即将开通","知道了");
			intent = new Intent(this,DoctorMyPartner.class);
			startActivity(intent);
			break;
		case R.id.my_salon://话题管理
			intent =new Intent(this,SalonAboutOthersActivity.class);
			intent.putExtra("type", "0");
			startActivity(intent);
			break;
		case R.id.my_service://服务设置
			intent = new Intent(this,DoctorSettingActivity.class);
			startActivity(intent);
			break;
		case R.id.my_huodong://活动参与
			intent = new Intent(this,ActivesListActivity.class);
			startActivity(intent);
			break;
		case R.id.my_guide://诊所指南
			intent = new Intent(this,DocotrStationHelperActivity.class);
			intent.putExtra("type","0");
			intent.putExtra("title","诊所指南");
			startActivity(intent);
			break;
		case R.id.leave_messgae_count://我的发布
			intent = new Intent(this,DoctorMessageBoardDoctor.class);
			intent.putExtra("title", "我的公告");
			startActivity(intent);
			break;
		case R.id.yingshou_nanager://我的经营
			intent =new Intent(this,BuyAndSellMainActivity.class);
			intent.putExtra("type", false);
			intent.putExtra("title","我的经营");
			startActivity(intent);
			break;
		case R.id.mian_association://专业学会
			intent=new Intent(this,ServerCenterListActivity.class);
			intent.putExtra("type",6);
			startActivity(intent);
			break;
		case R.id.title_right2://设首页
			if(SharePreUtils.updateLockState()){
				titleRightBtn2.setText("取消设首页");
			}else{
				titleRightBtn2.setText("设首页");
			}
			break;
		}
	}
	

	private class TabsPagerAdapter extends PagerAdapter{
		final List<View> views = new ArrayList<View>();
		public TextView messageNumber;
		private Button message_number_manage;//我的患者
		private Button message_number_partner;//我的合作者
		private Button message_number_talk;//我的话题
		public TabsPagerAdapter() {
			View v = getLayoutInflater().inflate(R.layout.doctor_home_main_table_fragment_one,null);
			v.findViewById(R.id.my_calendar).setOnClickListener(DoctorHomeMainActivity.this);
			v.findViewById(R.id.my_huanzhe).setOnClickListener(DoctorHomeMainActivity.this);
			v.findViewById(R.id.my_bingan).setOnClickListener(DoctorHomeMainActivity.this);
			v.findViewById(R.id.my_salon).setOnClickListener(DoctorHomeMainActivity.this);
			v.findViewById(R.id.yingshou_nanager).setOnClickListener(DoctorHomeMainActivity.this);
			v.findViewById(R.id.my_service).setOnClickListener(DoctorHomeMainActivity.this);
			v.findViewById(R.id.leave_messgae_count).setOnClickListener(DoctorHomeMainActivity.this);
			v.findViewById(R.id.my_guide).setOnClickListener(DoctorHomeMainActivity.this);
			v.findViewById(R.id.mian_association).setOnClickListener(DoctorHomeMainActivity.this);
			messageNumber=(TextView) v.findViewById(R.id.message_number_text);
			message_number_manage=(Button)v.findViewById(R.id.message_number_manage);
			message_number_partner=(Button)v.findViewById(R.id.message_number_partner);
			message_number_talk=(Button)v.findViewById(R.id.message_number_talk);
			views.add(v);
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}
		
		@Override
		public int getCount() {
			return views.size();
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View item = views.get(position);
			container.addView(item);
			return item;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View)object);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
	}
	
	private void queryDataCount(){
		//获取公告板未读条数
		HttpRestClient.doHttpMessageLeaveCount(new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				try {
					//公告板
					int count=Integer.valueOf(content);
					if(count>0){
						adapter.messageNumber.setVisibility(View.VISIBLE);
						adapter.messageNumber.setText(content);
					}else{
						adapter.messageNumber.setVisibility(View.GONE);
					}
					
					
				} catch (Exception e) {
				}
			}
		});
	}
	private void queryDataCountoOther(){
		HttpRestClient.doHttpMyZoneCount("20",SmartFoxClient.getLoginUserId(),SharePreUtils.fatchNewsReadedLastId(),SharePreUtils.fatchInterestWallId(),new JsonsfHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {
				super.onSuccess(statusCode, response);//新闻：80
				try{
					//患者管理
					if(response.getInteger("310")==0){
						ViewUtils.setGone(adapter.message_number_manage,true);
					}else{
						ViewUtils.setGone(adapter.message_number_manage,false);
						adapter.message_number_manage.setText(meSageCount( response.getIntValue("310")));
					}
					//合作者
					if(response.getInteger("300")==0){
						ViewUtils.setGone(adapter.message_number_partner,true);
					}else{
						ViewUtils.setGone(adapter.message_number_partner,false);
						adapter.message_number_partner.setText(meSageCount( response.getIntValue("300")));
					}
					//话题管理
					if(response.getInteger("320")==0){
						ViewUtils.setGone(adapter.message_number_talk,true);
					}else{
						ViewUtils.setGone(adapter.message_number_talk,false);
						adapter.message_number_talk.setText(meSageCount( response.getIntValue("320")));
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
	}
	//更新未读消息条数界面
	private String meSageCount(int count){
		String readCount;
		if(count!=0){
			readCount=count >100 ? "99+":String.valueOf(count);
		}else{
			readCount="0";
		}
		return readCount;
	}
}
